import random
import openpyxl
import re
import datetime
import os
import sys
import time
from openpyxl.drawing.image import Image

role_list = [
    {
        'name': 'President',
        'row': [6, 24],
        'col': 6,
        'value': 'cookie, cui'
    },
    {
        'name': 'TME',
        'row': [7, 23],
        'col': 6,
        'value': ''
    },
    {
        'name': 'Timer',
        'row': [9, 11, 17, 21],
        'col': 6,
        'value': ''
    },
    {
        'name': 'TTM',
        'row': 10,
        'col': 6,
        'value': ''
    },

    {
        'name': 'Speaker 1',
        'row': 13,
        'col': 6,
        'value': ''
    },
    {
        'name': 'Speaker 2',
        'row': 15,
        'col': 6,
        'value': ''
    },
    {
        'name': 'IE 1',
        'row': 19,
        'col': 6,
        'value': ''
    },
    {
        'name': 'IE 2',
        'row': 20,
        'col': 6,
        'value': ''
    },
    {
        'name': 'Photographer',
        'row': 25,
        'col': 6,
        'value': ''
    }
]


def color_set(text, color):
    color_dic = {
        'RED': '\033[31m',
        'GREEN': '\033[32m',
        'YELLOW': '\033[33m',
        'BLUE': '\033[34m',
        'FUCHSIA': '\033[35m',
        'CYAN': '\033[36m',
        'WHITE': '\033[37m',
        'NORMAL': '\033[0m'
    }
    color_text = color.upper()
    if color in color_dic.keys():
        return '%s %s %s' % (color_dic[color_text], text, color_dic['NORMAL'])
    else:
        return '%s %s %s' % (color_dic['NORMAL'], text, color_dic['NORMAL'])


def print_role(cell, value):
    print('%s: %s' % (cell['name'], value))


def print_init_info():
    info = '''\n--- 在 config.txt 文件中设置
    模板文件路径  sample: c:/TMC/template.xlsx
    Icon图像路径 sample: c:/TMC/icon.png ---\n'''
    print(color_set(info, 'GREEN'))


def read_line(line_num):
    with open('/Users/putao/Desktop/git/python/Practice100/Chapter3/TMC-Gen/config.txt', 'r') as file:
        lines = file.readlines()
        # print('file path is: ', lines[line_num])
        return lines[line_num]


class Agenda:
    def __init__(self, path, sheet):
        self.role_list = role_list
        self.path = path
        self.wb = openpyxl.load_workbook(path)
        self.ws = self.wb[sheet]
        self.insert_icon()
        self.set_meeting_number()
        self.set_meeting_date()

    def insert_icon(self):
        img_path = read_line(1)
        img = Image(img_path)
        img.width = 110
        img.height = 100
        self.ws.add_image(img, 'B1')
        print('图像已生成')

    def set_meeting_number(self):
        cell = self.ws['A4']
        value = cell.value
        number = re.findall(r'\d+', value)
        new_value = value.replace(number[0], str(int(number[0]) + 1))
        cell.value = new_value
        print('第', new_value, '次会议')

    def set_meeting_date(self):
        cell = self.ws['B2']
        value = cell.value
        value_list = value.split(' ')
        date = value_list[1]
        next_date = datetime.datetime.now() + datetime.timedelta(days=14)
        next_date = next_date.strftime('%Y/%m/%d')
        value_list[1] = next_date
        new_value = ' '.join(value_list)
        cell.value = new_value
        print('会议日期：', new_value)

    def set_role_takers(self):
        officers = ['Megan', 'Harry', 'Luca', 'Anna', 'Natalie', 'Echo']
        members = ['Travis', 'Ella', 'Monica', 'Jupy', 'Percy', 'Gloria']
        all_members = officers + members
        print('会员列表', all_members)
        for cell in self.role_list:
            if len(cell['value']) != 0:
                self.set_cell_value(cell, '')
                print_role(cell, cell['value'])
            else:
                index = random.randint(1, len(all_members) - 1)
                value = all_members[index]
                self.set_cell_value(cell, value)
                # remove the assigned member from list
                del all_members[index]
                print_role(cell, value)
        self.wb.save(self.path)
        print(color_set('\n--- 模板生成完成 ----', 'BLUE'))

    def set_cell_value(self, cell, value):
        if type(cell['row']) is list:
            for row_index in cell['row']:
                self.ws.cell(row=row_index, column=cell['col'], value=cell['value'] or value)
        else:
            self.ws.cell(row=cell['row'], column=cell['col'], value=cell['value'] or value)


if __name__ == '__main__':
    print_init_info()
    template = read_line(0).strip()
    # template = read_line(0).replace('\n', '')
    if os.path.exists(template):
        language = input('请输入下次会议是中文还是English(默认)： ').strip()
        if language == '中文' or language == 'Chinese':
            sheet_name = '中文'
        else:
            sheet_name = 'English'
        print(sheet_name + ' 模板在生成中...')
        agenda = Agenda(template, sheet_name)
        agenda.set_role_takers()
    else:
        print('模板文件路径: ' + template + '不存在，请创建模板文件')
